document.addEventListener('DOMContentLoaded', () => {
    const generateBtn = document.getElementById('generate-btn');
    const goalInput = document.getElementById('goal-input');
    const domainSelect = document.getElementById('domain-select');
    const planContainer = document.getElementById('plan-container');
    const loadingSpinner = document.getElementById('loading-spinner');

    generateBtn.addEventListener('click', async () => {
        const goal = goalInput.value.trim();
        const domain = domainSelect.value;

        if (!goal) {
            alert('请输入您的目标！');
            return;
        }

        // 显示加载动画，清空旧规划
        loadingSpinner.classList.remove('hidden');
        planContainer.innerHTML = '';

        try {
            const response = await fetch('http://127.0.0.1:5000/api/plan', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    goal: goal,
                    domain: domain
                }),
            });

            // 隐藏加载动画
            loadingSpinner.classList.add('hidden');

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || '服务器返回错误');
            }

            const plan = await response.json();
            renderPlan(plan);

        } catch (error) {
            // 隐藏加载动画
            loadingSpinner.classList.add('hidden');
            renderError(error.message);
            console.error('请求失败:', error);
        }
    });

    function renderPlan(plan) {
        if (plan.error) {
            renderError(plan.error);
            return;
        }

        let html = `
            <h2 class="plan-title">${plan.plan_title}</h2>
            <p class="plan-summary">${plan.plan_summary}</p>
        `;

        plan.stages.forEach(stage => {
            html += `
                <div class="stage">
                    <div class="stage-header">
                        <div class="stage-number">${stage.stage_number}</div>
                        <h3 class="stage-title">${stage.stage_title}</h3>
                    </div>
                    <p class="stage-description">${stage.stage_description}</p>
                    <div class="recommended-items">
                        <h4>推荐项目:</h4>
                        <ul>
                            ${stage.recommended_items.map(item => `<li>${item.item_title} (ID: ${item.item_id})</li>`).join('')}
                        </ul>
                    </div>
                    <p class="stage-reasoning"><strong>💡 理由:</strong> ${stage.reasoning}</p>
                </div>
            `;
        });

        planContainer.innerHTML = html;
    }

    function renderError(errorMessage) {
        planContainer.innerHTML = `<div class="error-message"><strong>出错了：</strong> ${errorMessage}</div>`;
    }
});
